// 游戏配置
const config = {
  size: 15,    // 棋盘尺寸
  cellSize: 40 // 格子大小
};

let board = [];     // 棋盘数据
let currentPlayer = 1; // 当前玩家（1-玩家，2-电脑）
let gameOver = false;
let difficulty = 1; // 难度等级（1-初级，2-中级，3-高级）

// 初始化游戏
function initGame() {
  const canvas = document.getElementById('board');
  canvas.width = config.size * config.cellSize;
  canvas.height = config.size * config.cellSize;
  
  // 初始化棋盘数据
  board = Array(config.size).fill().map(() => Array(config.size).fill(0));
  
  canvas.addEventListener('click', handleClick);
  drawBoard();
}

// 绘制棋盘
function drawBoard() {
  const canvas = document.getElementById('board');
  const ctx = canvas.getContext('2d');
  
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // 绘制网格
  for (let i = 0; i < config.size; i++) {
    ctx.beginPath();
    ctx.moveTo(i * config.cellSize + 0.5, 0.5);
    ctx.lineTo(i * config.cellSize + 0.5, canvas.height - 0.5);
    ctx.stroke();
    
    ctx.beginPath();
    ctx.moveTo(0.5, i * config.cellSize + 0.5);
    ctx.lineTo(canvas.width - 0.5, i * config.cellSize + 0.5);
    ctx.stroke();
  }
  
  // 绘制棋子
  for (let i = 0; i < config.size; i++) {
    for (let j = 0; j < config.size; j++) {
      if (board[i][j] !== 0) {
        ctx.beginPath();
        ctx.arc(
          i * config.cellSize + config.cellSize/2,
          j * config.cellSize + config.cellSize/2,
          config.cellSize/2 - 2,
          0,
          Math.PI * 2
        );
        ctx.fillStyle = board[i][j] === 1 ? 'black' : 'white';
        ctx.fill();
      }
    }
  }
}

// 处理玩家点击
function handleClick(e) {
  if (gameOver || currentPlayer !== 1) return;
  
  const rect = e.target.getBoundingClientRect();
  const x = Math.floor((e.clientX - rect.left) / config.cellSize);
  const y = Math.floor((e.clientY - rect.top) / config.cellSize);
  
  if (board[x][y] === 0) {
    placePiece(x, y, 1);
    if (checkWin(x, y, 1)) {
      gameOver = true;
      setTimeout(() => alert('玩家胜利！'), 10);
      return;
    }
    currentPlayer = 2;
    setTimeout(computerMove, 500);
  }
}

// 电脑移动
function computerMove() {
  let move;
  switch(difficulty) {
    case 1:
      move = getRandomMove();
      break;
    case 2:
      move = getIntermediateMove();
      break;
    case 3:
      move = getAdvancedMove();
      break;
  }
  
  if (move) {
    placePiece(move.x, move.y, 2);
    if (checkWin(move.x, move.y, 2)) {
      gameOver = true;
      setTimeout(() => alert('电脑胜利！'), 10);
    }
    currentPlayer = 1;
  }
}

// 初级难度：随机移动
function getRandomMove() {
  let available = [];
  for (let i = 0; i < config.size; i++) {
    for (let j = 0; j < config.size; j++) {
      if (board[i][j] === 0) available.push({x: i, y: j});
    }
  }
  return available[Math.floor(Math.random() * available.length)];
}

// 中级难度：简单评估
function getIntermediateMove() {
  let bestScore = -1;
  let bestMoves = [];
  
  // 评估函数
  function evaluate(x, y, player) {
    let score = 0;
    const directions = [[1,0],[0,1],[1,1],[1,-1]];
    
    directions.forEach(([dx, dy]) => {
      let playerCount = 1, computerCount = 1;
      
      // 正向检测
      for (let i = 1; i < 5; i++) {
        const nx = x + dx * i;
        const ny = y + dy * i;
        if (nx < 0 || nx >= config.size || ny < 0 || ny >= config.size) break;
        if (board[nx][ny] === 1) playerCount++;
        else break;
      }
      
      // 反向检测
      for (let i = 1; i < 5; i++) {
        const nx = x - dx * i;
        const ny = y - dy * i;
        if (nx < 0 || nx >= config.size || ny < 0 || ny >= config.size) break;
        if (board[nx][ny] === 1) playerCount++;
        else break;
      }
      
      // 电脑棋子检测
      for (let i = 1; i < 5; i++) {
        const nx = x + dx * i;
        const ny = y + dy * i;
        if (nx < 0 || nx >= config.size || ny < 0 || ny >= config.size) break;
        if (board[nx][ny] === 2) computerCount++;
        else break;
      }
      
      // 评分规则
      if (playerCount >= 4) score += 1000;  // 阻止玩家四连
      else if (playerCount === 3) score += 100;
      if (computerCount >= 4) score += 500; // 完成电脑四连
      else if (computerCount === 3) score += 200;
    });
    
    return score;
  }

  // 遍历所有空位
  for (let x = 0; x < config.size; x++) {
    for (let y = 0; y < config.size; y++) {
      if (board[x][y] === 0) {
        const score = evaluate(x, y, 2);
        if (score > bestScore) {
          bestScore = score;
          bestMoves = [{x, y}];
        } else if (score === bestScore) {
          bestMoves.push({x, y});
        }
      }
    }
  }
  
  // 从最佳选择中随机选一个
  return bestMoves[Math.floor(Math.random() * bestMoves.length)] || getRandomMove();
}

// 高级难度：Minimax算法
function getAdvancedMove() {
  // 实现Minimax算法（示例代码）
  return getRandomMove(); // 暂时使用随机
}

// 放置棋子
function placePiece(x, y, player) {
  board[x][y] = player;
  drawBoard();
}

// 检查胜利条件
function checkWin(x, y, player) {
  const directions = [
    [1, 0],  // 水平
    [0, 1],  // 垂直
    [1, 1],  // 正对角线
    [1, -1]  // 反对角线
  ];

  for (let [dx, dy] of directions) {
    let count = 1;
    for (let i = 1; i < 5; i++) {
      const nx = x + dx * i;
      const ny = y + dy * i;
      if (nx >= 0 && nx < config.size && ny >= 0 && ny < config.size && board[nx][ny] === player) {
        count++;
      } else {
        break;
      }
    }
    for (let i = 1; i < 5; i++) {
      const nx = x - dx * i;
      const ny = y - dy * i;
      if (nx >= 0 && nx < config.size && ny >= 0 && ny < config.size && board[nx][ny] === player) {
        count++;
      } else {
        break;
      }
    }
    if (count >= 5) return true;
  }
  return false;
}

// 难度选择
document.querySelectorAll('.difficulty-btn').forEach(btn => {
  btn.addEventListener('click', () => {
    difficulty = parseInt(btn.dataset.level);
    document.getElementById('difficulty').textContent = ['初级', '中级', '高级'][difficulty - 1];
    resetGame();
  });
});

// 重新开始游戏
function resetGame() {
  board = Array(config.size).fill().map(() => Array(config.size).fill(0));
  currentPlayer = 1;
  gameOver = false;
  drawBoard();
}

// 初始化游戏
initGame();
